package com.hellobike.haxing.modules.purchase.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.system.base.controller.BaseController;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.purchase.common.TimerUtil;
import com.hellobike.haxing.modules.purchase.dto.TPurchaseProDto;
import com.hellobike.haxing.modules.purchase.entity.TPurchaseInfo;
import com.hellobike.haxing.modules.purchase.entity.TPurchaseOrder;
import com.hellobike.haxing.modules.purchase.entity.TPurchaseOrderDetail;
import com.hellobike.haxing.modules.purchase.entity.TPurchasePro;
import com.hellobike.haxing.modules.purchase.service.ITPurchaseInfoService;
import com.hellobike.haxing.modules.purchase.service.ITPurchaseOrderDetailService;
import com.hellobike.haxing.modules.purchase.service.ITPurchaseOrderService;
import com.hellobike.haxing.modules.purchase.service.ITPurchaseProService;
import com.hellobike.haxing.modules.supplier.entity.TSupplierClPro;
import com.hellobike.haxing.modules.supplier.service.ITSupplierClProRecordService;
import com.hellobike.haxing.modules.supplier.service.ITSupplierClProService;
import com.hellobike.haxing.modules.supplier.util.BeanUtils;
import com.hellobike.haxing.modules.supplier.util.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
 * @Description: 商品列表
 * @Author: haxing-boot
 * @Date:   2020-01-20
 * @Version: V1.0
 */
@RestController
@RequestMapping("/purchase/tPurchasePro")
@Slf4j
public class TPurchaseProController extends BaseController<TPurchasePro, ITPurchaseProService> {
	@Autowired
	private ITPurchaseProService tPurchaseProService;
	@Autowired
	private ITPurchaseOrderService tPurchaseOrderService;
	@Autowired
	private ITPurchaseOrderDetailService tPurchaseOrderDetailService;
	@Autowired
	private ITSupplierClProService tSupplierClProService;
	@Autowired
	private ITPurchaseInfoService tPurchaseInfoService;
	@Autowired
	private ITSupplierClProRecordService itSupplierClProRecordService;

	/**
	 * 分页列表查询
	 *
	 * @param tPurchasePro
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "商品列表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(TPurchasePro tPurchasePro,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<TPurchasePro> queryWrapper = QueryGenerator.initQueryWrapper(tPurchasePro, req.getParameterMap());
		Page<TPurchasePro> page = new Page<TPurchasePro>(pageNo, pageSize);
		IPage<TPurchasePro> pageList = tPurchaseProService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	/**
	 * 分页列表查询
	 *
	 * @param tPurchasePro
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "商品列表-分页列表查询")
	@PostMapping(value = "/list2")
	public Result<?> list2(TPurchasePro tPurchasePro,
						   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
						   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
						   HttpServletRequest req) {
		QueryWrapper<TPurchasePro> queryWrapper = QueryGenerator.initQueryWrapper(tPurchasePro, req.getParameterMap());
		Page<TPurchasePro> page = new Page<TPurchasePro>(pageNo, pageSize);
		IPage<TPurchasePro> pageList = tPurchaseProService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	/**
	 *   添加
	 *
	 * @param tPurchasePro
	 * @return
	 */
	@AutoLog(value = "商品列表-添加",operateType=2)
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody TPurchasePro tPurchasePro) {
		tPurchaseProService.save(tPurchasePro);
		return Result.ok("添加成功！");
	}
	/**
	 *   添加
	 *
	 * @param tPurchasePro
	 * @return
	 */
	@AutoLog(value = "商品列表-添加",operateType=2)
	@PostMapping(value = "/addtos")
	public Result<?> addtos(@RequestBody List<TPurchasePro> tPurchasePro) {
//		 tPurchaseProService.save(tPurchasePro);
		return Result.ok("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param tPurchasePro
	 * @return
	 */
	@AutoLog(value = "商品列表-编辑",operateType=3)
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody TPurchasePro tPurchasePro) {
		tPurchaseProService.updateById(tPurchasePro);
		return Result.ok("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "商品列表-删除",operateType=4)
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) Long id) {
		tPurchaseProService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 *  编辑
	 *
	 * @param tPurchasePro
	 * @return
	 */
	@AutoLog(value = "修改供应商",operateType=3)
	@PutMapping(value = "/editSupplier")
	public Result<?> editSupplier(@RequestBody TPurchasePro tPurchasePro) {
		tSupplierClProService.updateClpDefault(tPurchasePro.getSkuId(),tPurchasePro.getSupplierId(), Constant.IS_DEFAULT);
		tPurchaseProService.editSupplier(tPurchasePro);
		return Result.ok("编辑成功!");
	}

	/**
	 *  编辑
	 *
	 * @param tPurchasePro
	 * @return
	 */
	@AutoLog(value = "修改供应商",operateType=3)
	@PutMapping(value = "/editSupplierByRecord")
	public Result<?> editSupplierByRecord(@RequestBody TPurchasePro tPurchasePro) {
		tPurchaseProService.editSupplierByRecord(tPurchasePro);
		return Result.ok("编辑成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param json
	 * @return
	 */
	@PostMapping(value = "/detail")
	public Result<?> detail(@RequestBody JSONObject json) {
		Long id = json.getLong("headerId");

		QueryWrapper<TPurchaseInfo> tPurchaseInfoQueryWrapper = new QueryWrapper<>();
		tPurchaseInfoQueryWrapper.eq("id", id);
		TPurchaseInfo tPurchaseInfo  = tPurchaseInfoService.getOne(tPurchaseInfoQueryWrapper);

		List<TPurchasePro> res = new ArrayList<>();
		QueryWrapper<TPurchasePro> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("warehouse_id", tPurchaseInfo.getWarehouseId());
		queryWrapper.eq("supplier_id", tPurchaseInfo.getSupplierId());
		queryWrapper.ge("update_time", TimerUtil.getStart23Date(tPurchaseInfo.getCreateTime()));
		queryWrapper.le("update_time", TimerUtil.getEnd23Date(tPurchaseInfo.getCreateTime()));
		List<TPurchasePro> tPurchaseProLists = tPurchaseProService.list(queryWrapper);
		if(tPurchaseProLists==null) {
			return Result.error("未找到对应数据");
		}else{
			tPurchaseProLists.forEach(
					item -> {
						QueryWrapper<TPurchaseOrderDetail> orderQuery = new QueryWrapper<>();
						orderQuery.eq("sku_id", item.getSkuId());
						orderQuery.eq("supplier_id", item.getSupplierId());
						orderQuery.ge("create_time", TimerUtil.getStart23Date(tPurchaseInfo.getCreateTime()));
						orderQuery.le("create_time", TimerUtil.getEnd23Date(tPurchaseInfo.getCreateTime()));
						List<TPurchaseOrderDetail> orderDetails = tPurchaseOrderDetailService.list(orderQuery);
						if(orderDetails != null && orderDetails.size() > 0){
							for(TPurchaseOrderDetail tPurchaseOrderDetail : orderDetails) {
								TPurchasePro show = new TPurchasePro();
								BeanUtils.copyProperties(item,show);
								show.setPurchaseVolume(tPurchaseOrderDetail.getPurchaseVolume());
								show.setSupplierName(tPurchaseOrderDetail.getSupplierName());
								show.setPurchaseOrderIds(tPurchaseOrderDetail.getParentOrderCode());
								res.add(show);
							}
						}
					}
			);
		}
		return Result.ok(res);
	}


	/**
	 * 通过id查询采购价
	 *
	 * @param json
	 * @return
	 */
	@PostMapping(value = "/purchasePrice")
	public Result<?> purchasePrice(@RequestBody JSONObject json) {
		Long id = json.getLong("headerId");
		QueryWrapper<TPurchasePro> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("id", id);
		List<TPurchasePro> tPurchaseProLists = tPurchaseProService.list(queryWrapper);
		if(tPurchaseProLists==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(tPurchaseProLists);
	}

	/**
	 *  编辑采购价
	 *
	 * @param tPurchasePro
	 * @return
	 */
	@AutoLog(value = "编辑采购价",operateType=3)
	@PutMapping(value = "/editPurchasePrice")
	public Result<?> editPurchasePrice(@RequestBody TPurchasePro tPurchasePro) {
		TPurchasePro updateDo = new TPurchasePro();
		updateDo.setId(tPurchasePro.getId());
		updateDo.setPurchasePrice(tPurchasePro.getPurchasePrice());
		tPurchaseProService.updateById(updateDo);

		// 修改clp
		tSupplierClProService.updateClp(tPurchasePro.getSkuId(),tPurchasePro.getPurchasePrice());
		return Result.ok("编辑成功!");
	}
	/**
	 * 通过id查询
	 *
	 * @param json
	 * @return
	 */
	@PostMapping(value = "/getOrder")
	public Result<?> getOrder(@RequestBody JSONObject json) {
		Long id = json.getLong("headerId");
		TPurchasePro tPurchasePro = tPurchaseProService.getById(id);
		if(tPurchasePro == null){
			return Result.error("未找到对应数据");
		}else {
			QueryWrapper<TPurchaseOrder> queryPro = new QueryWrapper<>();
			queryPro.eq("sku_id", tPurchasePro.getSkuId());
			List<TPurchaseOrder> tPurchaseOrders = tPurchaseOrderService.list(queryPro);
			if (tPurchaseOrders == null) {
				return Result.error("未找到对应数据");
			} else {
				for(TPurchaseOrder tPurchaseOrder : tPurchaseOrders){
					if(tPurchasePro.getPurchaseVolume().equals(tPurchaseOrder.getPurchaseVolume())){
						return Result.ok(tPurchaseOrder);
					}
				}
			}
		}
		return Result.error("未找到对应数据");
	}

	/**
	 *
	 * @return
	 */
	@PostMapping(value = "/getAllPro")
	public void getAllPro() {
		//tPurchaseProService.getAllPro();
	}

	/**
	 *
	 * @return
	 */
	@PostMapping(value = "/test")
	public void test() {
		//tPurchaseProService.test();
	}


	/**
	 *
	 * @return
	 */
	@PostMapping(value = "/syncProAndClp")
	public void syncProAndClp() {
		TPurchaseProDto test = new TPurchaseProDto();
		test.setSkuId(141l);
		tPurchaseProService.syncProAndClp(test);
	}



	/**
	 * 通过id查询
	 *
	 * @param json
	 * @return
	 */
	@PostMapping(value = "/getPurchaseOrder")
	public Result<?> getPurchaseOrder(@RequestBody JSONObject json) {
		Long id = json.getLong("headerId");
		TPurchaseOrder tPurchaseOrder = tPurchaseOrderService.getById(id);
		if(tPurchaseOrder == null){
			return Result.error("未找到对应数据");
		}else {
			return Result.ok(tPurchaseOrder);
		}
	}

	/**
	 * 通过id查询
	 *
	 * @param json
	 * @return
	 */
	@PostMapping(value = "/getPurchasePro")
	public Result<?> getPurchasePro(@RequestBody JSONObject json) {
		Long id = json.getLong("headerId");
		TPurchasePro tPurchasePro = tPurchaseProService.getById(id);
		if(tPurchasePro == null){
			return Result.error("未找到对应数据");
		}else {
			QueryWrapper<TSupplierClPro> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("supplier_id", tPurchasePro.getSupplierId());
			queryWrapper.eq("sku_id", tPurchasePro.getSkuId());
			TSupplierClPro tSupplierClPro = tSupplierClProService.getOne(queryWrapper);
			if(tSupplierClPro != null){
				tPurchasePro.setSupplyVolume(tSupplierClPro.getSupplyVolume());
				tPurchasePro.setSupplierPrice(tSupplierClPro.getSupplierPrice());
			}
			return Result.ok(tPurchasePro);
		}
	}


	/**
	 * 通过id查询供货商价格信息
	 *
	 * @param json
	 * @return
	 */
	@PostMapping(value = "/getNewSupplier")
	public Result<?> getNewSupplier(@RequestBody JSONObject json) {
		String ids = json.getString("headerId");
		String[] idArg = ids.split(",");
		Long supplierId = null;
		Long proId = null;
		if(idArg[0] != null && idArg[1] != null){
			supplierId = Long.valueOf(idArg[0]);
			proId = Long.valueOf(idArg[1]);
		}
		QueryWrapper<TSupplierClPro> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("supplier_id", supplierId);
		TSupplierClPro tSupplierClPro = tSupplierClProService.getOne(queryWrapper);

		QueryWrapper<TPurchaseOrder> queryPro = new QueryWrapper<>();
		queryPro.eq("id", proId);
		TPurchaseOrder tPurchaseOrder = tPurchaseOrderService.getOne(queryPro);
		BeanUtils.copyProperties(tSupplierClPro,tPurchaseOrder);
		tPurchaseOrder.setPurchaseVolume(null);
		return Result.ok(tPurchaseOrder);
	}

	/**
	 * getWareHouse
	 *
	 * @return
	 */
	@PostMapping(value = "/getWareHouse")
	public Result<?> getWareHouse(@RequestBody JSONObject json) {
		return Result.ok(tPurchaseProService.getWareHouse(json.getLong("headerId")));
	}


	/**
	 * 通过id查询供货商价格信息
	 *
	 * @param json
	 * @return
	 */
	@PostMapping(value = "/getNewSupplier2")
	public Result<?> getNewSupplier2(@RequestBody JSONObject json) {
		String ids = json.getString("headerId");
		String[] idArg = ids.split(",");
		Long supplierId = null;
		Long skuId = null;
		Long id = null;
		if(idArg[0] != null && idArg[1] != null){
			supplierId = Long.valueOf(idArg[0]);
			skuId = Long.valueOf(idArg[1]);
			id = Long.valueOf(idArg[2]);
		}
		QueryWrapper<TSupplierClPro> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("supplier_id", supplierId);
		queryWrapper.eq("sku_id", skuId);
		TSupplierClPro tSupplierClPro = tSupplierClProService.getOne(queryWrapper);
		if(tSupplierClPro != null){
			tSupplierClPro.setId(id);
		}
		return Result.ok(tSupplierClPro);
	}


	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "商品列表-批量删除",operateType=4)
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.tPurchaseProService.removeByIds(Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 通过id生成供应商信息
	 *
	 * @param json
	 * @return
	 */
	@PostMapping(value = "/getProById")
	public Result<?> getProById(@RequestBody JSONObject json) {
		QueryWrapper<TSupplierClPro> queryWrapper = new QueryWrapper<>();
		Long headerId = json.getLong("headerId");
		return Result.ok(tPurchaseProService.getById(headerId));
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) Long id) {
		TPurchasePro tPurchasePro = tPurchaseProService.getById(id);
		if(tPurchasePro==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(tPurchasePro);
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param tPurchasePro
	 */
	@AutoLog(value = "商品列表-导出excel",operateType=6)
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, TPurchasePro tPurchasePro) {
		return super.exportXls(request, tPurchasePro, TPurchasePro.class, "商品列表");
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@AutoLog(value = "商品列表-导入excel",operateType=5)
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, TPurchasePro.class);
	}

}
